<template>
  <div class="editInfo">
    <hmNavBar
      :title="titleObj[type]"
      path="/home/myInfo"
      rightText="保存"
      @rightClick="save"
    ></hmNavBar>
    <div class="content">
      <van-field
        v-if="type !== 'photo'"
        v-model="inputValue"
        class="field"
      ></van-field>
      <van-uploader
        v-else
        v-model="list"
        max-count="1"
        :before-read="beforeRead"
        :after-read="afterRead"
      ></van-uploader>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { userOwnData, editData } from '@/api/my.js'
export default {
  computed: {
    ...mapState(['userInfo'])
  },
  data () {
    return {
      inputValue: '',
      type: this.$route.query.type,
      titleObj: {
        name: '修改昵称',
        mobile: '修改手机号',
        photo: '修改头像'
      },
      list: []
    }
  },
  created () {
    //   如果有头像 list: [{url: 图像地址}]
    // 没有头像就不要操作
    // if (this.userInfo.photo) {
    //   this.list[0] = { url: this.userInfo.photo }
    // }
    window.console.log(this.userInfo)
    this.inputValue = this.userInfo[this.type]
  },
  methods: {
    save () {
      //   alert('保存')
      this.editData({
        [this.type]: this.inputValue
      })
    },
    // 编辑用户信息
    editData (obj) {
      this.$toast.loading({
        duration: 0
      })
      userOwnData(obj).then(() => {
        //   window.console.log(res)
        this.$toast.success('修改资料成功')
        this.$router.push('/home/myInfo')
        // 更新vuex中的userInfo
        this.$store.dispatch('refreshUserInfo')
      })
    },
    // 上传头像前
    beforeRead (file) {
      const isImg = file.type === 'image/png'
      const limit2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$toast.fail('请上传PNG格式图片')
      }
      if (!limit2M) {
        this.$toast.fail('请上传2M内大小的图片')
      }
      return isImg && limit2M
    },
    // 读取头像后
    afterRead (res) {
      // 上传头像到服务器
      const _formData = new FormData()
      _formData.append('files', res.file)
      this.$toast.loading({
        duration: 0
      })
      editData(_formData).then(res => {
        this.$toast.success('上传成功')
        window.console.log(res)
        this.inputValue = res.data.id
      })
    }
  }
}
</script>
<style lang="less" scoped>
.editInfo {
  .content {
    padding: 20px 15px;
    text-align: center;
    .field {
      background-color: #f7f4f5;
      border-radius: 25px;
    }
  }
}
</style>
